<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    :body-style="{ height: '450px' }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { computed, defineComponent, inject, ref, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { EpibolyPersonFormSchema } from '/src/views/ehs/epiboly/epiboly.data';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { addEpibolyPerson, updateEpibolyPerson } from '/@/api/ehs/epiboly';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { EpibolyPersonDto } from '/@/api/ehs/model/epibolyModel';
  import registerForm from "/@/views/sys/login/RegisterForm.vue";

  export default defineComponent({
    name: 'AddOrUpdateEpibolyPerson.vue',
    components: { BasicForm, BasicModal },
    setup(_, { emit }) {
      const {createMessage} = useMessage();
      console.log('AddOrUpdateEpibolyPerson.vue setup');

      const op = ref(OperationTypeEnum.UN_KNOWN);
      const personId = ref('');
      const unitId = ref('');
      const orgcode = ref('');

      // 注入模块名称
      const moduleName = inject<string>('moduleName') || '相关方人员';
      const modalTitle = ref('相关方人员');

      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: EpibolyPersonFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      })

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }]=useModalInner(async(data)=> {
        console.log('AddOrUpdateEpibolyPerson.vue useModalInner data', data);

        // 保存传入的参数
        if (data != undefined) {
          qcUnifyProps.value = unref(data);
        }

        // 接收父组件传递的数据
        if (data?.operateType) {
          op.value = data.operateType;
        }

        if (data?.id) {
          personId.value = data.id;
        }

        if (data?.unitId) {
          unitId.value = data.unitId;
        }

        if (data?.orgcode) {
          orgcode.value = data.orgcode;
        }

        // 设置模态框标题
        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value !== OperationTypeEnum.UN_KNOWN && op.value !== OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        resetFields(); // 重置表单
        setModalProps({ confirmLoading: false });

        // 始终设置组织代码和单位ID
        const defaultData: any = {};
        if (orgcode.value) {
          defaultData.orgcode = orgcode.value;
        }
        if (unitId.value) {
          defaultData.unitid = unitId.value;
        }

        // 根据操作类型设置表单数据
        if (op.value === OperationTypeEnum.EDIT && data?.data) {

          const formData = {
            ...data.data,
            ...defaultData, // 确保组织代码和单位ID不丢失
            status: String(data.data.status || '1') // 确保状态是字符串
          };

          setFieldsValue(formData);

        } else if (op.value === OperationTypeEnum.ADD) {

          // 新增模式，设置默认值
          const addData = {
            ...defaultData,
            status: '1' // 默认状态
          };

          setFieldsValue(addData);
        }

      })

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        try {
          const values = await validate()
          setModalProps({ confirmLoading: true });

          // 创建一个符合EpibolyPersonDto接口的数据对象
          const epibolyPersonData: EpibolyPersonDto = {
            ...values,
            orgcode: orgcode.value,
            unitid: unitId.value
          }

          try {
            if (op.value === OperationTypeEnum.ADD) {
              // 调用接口进行保存
              const res = await addEpibolyPerson(epibolyPersonData);
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('员工保存成功。', 2);
              }else {

              }
              opSuccess();
            } else if (op.value === OperationTypeEnum.EDIT) {
              // 调用接口进行保存
              const updateData = {
                ...epibolyPersonData,
                id: personId.value // 确保更新时包含ID
              };
              const res = await updateEpibolyPerson(updateData);
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('员工修改成功。', 2);
              }
              opSuccess();
            } else {
              createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
            }
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } catch (error) {

          console.error('员工表单验证失败:', error)
        }
      }

      // 操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      return {
        displayModuleTitle,
        registerForm,
        opSuccess,
        registerModal,
        onButtonOkClick,
      };
    }
  });
</script>

<style scoped lang="less"></style>
